<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-alert title="注意:只允许为第三级分类添加商品参数" :closable="false" type="warning" show-icon></el-alert>
      <el-row>
        <el-col class="cat_opt">
          <span>选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->

          <el-cascader
            :props="cascaderProps"
            :options="cateList"
            expandTrigger="hover"
            v-model="selectOptions"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
          <!-- 标签页面 -->
          <el-tabs v-model="activeName" @tab-click="handleTagClick">
            <el-tab-pane label="动态参数" name="many">
              <el-button type="primary" :disabled="isButton" @click="showDialog">添加参数</el-button>
              <el-table :data="manyTableData" border stripe>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag
                      v-for="(item,index) in scope.row.attr_vals"
                      :key="index"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>

                    <!-- 添加按钮 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作" prop="attr_name">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="getEditInfo(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="removeParams(scope.row.attr_id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
              <el-button type="primary" :disabled="isButton" @click="showDialog">添加属性</el-button>
              <el-table :data="onlyTableData" border stripe>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                <el-table-column label="操作" prop="attr_name">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click="getEditInfo(scope.row.attr_id)"
                    >编辑</el-button>
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="removeParams(scope.row.attr.id)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closedDialog"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="80px" prop="attr_name">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="dialogVisible=false">取 消</el-button>
      <el-button type="primary" @click="addParams">确 定</el-button>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editclosedDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
        prop="attr_name"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="editdialogVisible=false">取 消</el-button>
      <el-button type="primary" @click="editParams">确 定</el-button>
    </el-dialog>
  </div>
</template>



<script>
export default {
  data() {
    return {
      cateList: [],
      //   级联选择框的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //  选择框数组
      selectOptions: [],
      activeName: "many",
      onlyTableData: [],
      manyTableData: [],
      dialogVisible: false,
      addForm: {
        attr_name: ""
      },
      rules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      },
      //   编辑表单
      editForm: {
        attr_name: ""
      },
      //   修改表单的验证规则
      editRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ]
      },
      editdialogVisible: false,

      inputVisible: false,
      inputValue: ""
    };
  },
  created() {
    this.getCateList();
  },
  computed: {
    //   定义计算属性判断用户是否选择的第三级属性
    isButton() {
      if (this.selectOptions.length !== 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.selectOptions.length === 3) {
        return this.selectOptions[2];
      }
      return null;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态参数";
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.$message.success("获取商品成功！");
      this.cateList = res.data;
      console.log(this.cateList);
    },
    handleChange() {
      console.log(this.selectOptions);
      this.getParamsInfo();
    },
    // 获取参数列表数组
    async getParamsInfo() {
      if (this.selectOptions.length !== 3) {
        this.selectOptions = [];
        this.onlyTableData = [];
        this.manyTableData = [];
        return;
      }
      // 根据所选分类的ID和当前所处的面板 获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );

      console.log(res.data, "参数列表数组");
      if (res.meta.status !== 200) return this.$message.error("获取参数失败");
      this.$message.success("获取商品成功！");
      res.data.forEach(item => {
        //   分割对象成数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // tag点击事件
    handleTagClick() {
      this.getParamsInfo();
    },
    showDialog() {
      this.dialogVisible = true;
    },
    closedDialog() {
      this.$refs.addFormRef.resetFields();
    },
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加参数失败");
        this.$message.success("添加参数成功！");
        this.dialogVisible = false;
        this.getParamsInfo();
      });
    },
    editclosedDialog() {
      this.$refs.editFormRef.resetFields();
    },
    // 点击按钮修改分类操作
    editParams() {
      // 查询当前参数信息
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_sel: this.activeName,
            attr_name: this.editForm.attr_name
          }
        );
        if (res.meta.status !== 200) return this.$message.error("修改参数失败");
        this.$message.success("修改参数成功！");
      });
    },

    async getEditInfo(id) {
      console.log(id);
      // 查询当前参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      );

      if (res.meta.status !== 200) return this.$message.error("获取参数失败");
      this.$message.success("获取参数成功！");
      this.editForm = res.data;
      this.editdialogVisible = true;
    },
    editDialog() {
      this.editdialogVisible = !this.editdialogVisible;
    },
    async removeParams(attr_id) {
      console.log(attr_id, "ididididi");
      // 删除参数
      const result = await this.$confirm(
        "此操作删除改参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (!result == "confirm") return false;
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除参数失败");
      this.$message.success("删除参数成功！");
      this.getParamsInfo();
    },
    handleInputConfirm() {
      this.inputValue;
    },
    showInput(row) {
      console.log(row.$refs);
      // $nextTick方法的作用  当页面上元素重新渲染之后
      // 才会指定回调函数中的代码
      row.inputVisible = true;
      this.$nextTick(_ => {
        //文本框自动获得焦点
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 文本框失去焦点触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      this.attrAlter(row);
    },

    async attrAlter(row) {
      // 对标签进行操作
      row.attr_vals.push(row.inputValue.trim());
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join("")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("修改参数失败");
      this.$message.success("修改成功！");
    },
    handleClose(i, row) {
      //删除对应的标签
      row.attr_vals.splice(i, 1);
    }
  }
};
</script>


<style lang="less" scoped>
.cat_opt {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}

.el-tag {
  margin: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>